package org.bleep.physics;

import org.bleep.util.Color;
import org.bleep.physics.Vector2D;
import org.bleep.util.Drawable;
import org.bleep.util.Interpolated;

import org.lwjgl.opengl.GL11;

import java.util.Random;

public class ParticleSystem implements Drawable, Interpolated
{
	private int ttl;
	
	private int numParticles;
	private Color color;
	private Particle[] particles;
	private Vector2D gravity;
	private Vector2D forceAccumulator;
	
	public ParticleSystem(int numParticles, float force, Color color, float x, float y)
	{
		Random r = new Random();
		
		forceAccumulator = new Vector2D(0f, 0f);
		
		gravity = new Vector2D(0, -50f);
		
		ttl = 300;
		
		float mass = 1f;
		
		this.numParticles = numParticles;
		this.color = color;
		particles = new Particle[numParticles];
		for (int i = 0; i < numParticles; i++)
		{
			double theta = r.nextDouble() * (2.0 * Math.PI);
			Vector2D v = Vector2D.withMagAndAngle(force, theta);
			
			Particle particle = new Particle(new Vector2D(x, y), r.nextFloat() * mass);
			particle.addForce(v);
			particles[i] = particle;
		}
	}
	
	public void update(float timeStep)
	{
		ttl--;
		for (int i = 0; i < numParticles; i++)
		{
			Particle particle = particles[i];
			particle.addForce(forceAccumulator);
			particle.addForce(Vector2D.mult(gravity, particle.getMass()));
			particle.update(timeStep);
		}
		forceAccumulator.zero();
	}
	
	public void addForce(Vector2D force)
	{
		forceAccumulator.add(force);
	}
	
	public void draw()
	{
		GL11.glDisable(GL11.GL_TEXTURE_2D);
		
		GL11.glBegin(GL11.GL_POINTS);
		color.glColor();
		
		for (int i = 0; i < numParticles; i++)
		{
			GL11.glVertex2i((int)(particles[i].getPosition().getX() + 0.5f), (int)(particles[i].getPosition().getY() + 0.5f));
		}
		
		GL11.glEnd();
		GL11.glEnable(GL11.GL_TEXTURE_2D);
	}
	
	public boolean isAlive()
	{
		return ttl > 0;
	}
}